﻿using SXICE.Core.Configs;
using SXICE.Core.Helpers;
using System;
using System.Collections.Concurrent;

namespace SXICE.Core.Infrastructure
{
    /// <summary>
    /// 默认的分布式缓存
    /// </summary>
    public class DefaultDistributedCache : IDistributedCache
    {
        /// <summary>
        /// 缓存
        /// </summary>
        private readonly ConcurrentDictionary<string, object> keyValuePairs = new ConcurrentDictionary<string, object>();

        public DefaultDistributedCache()
        {
            var cacheConfig = RuntimeHelper.Resolve<CacheConfigs>();
        }

        public bool Exists(string key)
        {
            return keyValuePairs.ContainsKey(key);
        }

        public void Remove(string key)
        {
            keyValuePairs.TryRemove(key, out var value);
        }

        public void Set<T>(string key, T value, TimeSpan? slideExpireTime = null, DateTime? absoluteExpireTime = null)
        {
            keyValuePairs.AddOrUpdate(key, value, (a, b) => value);
        }

        public bool TryGet<T>(string key, out T obj)
        {
            var result = keyValuePairs.TryGetValue(key, out var value);
            obj = (T)value;
            return result;
        }

        public T GetOrAdd<T>(string key, Func<T> func, TimeSpan? slidingExpiration = null, DateTime? absoluteExpiration = null)
        {
            if (keyValuePairs.TryGetValue(key, out var obj))
                return (T)obj;
            return (T)keyValuePairs.GetOrAdd(key, func());
        }

        public void AddOrUpdate<T>(string key, T obj)
        {
            keyValuePairs.AddOrUpdate(key, obj, (k, v) => obj);
        }

        public void Subscribe(string chancel, Action<string, string> action)
        {
            throw new NotImplementedException("默认分布式缓存没有此方法");
        }

        public void Publish(string chancel, string value)
        {
            throw new NotImplementedException("默认分布式缓存没有此方法");
        }

        public bool AcquireLock(string key, TimeSpan expire)
        {
            throw new NotImplementedException("默认分布式缓存没有此方法");
        }

        public bool ReleaseLock(string key)
        {
            throw new NotImplementedException("默认分布式缓存没有此方法");
        }
    }
}
